import { LOGIN_INFO_KEY, TENANT_ID, TOKEN_KEY, USER_INFO_KEY } from '@/enums/cacheEnum';
import { getAuthCache, getToken, setAuthCache } from '@/utils/auth';
import { defineStore } from 'pinia';
import { store } from '@/store';
import { GetUserInfoModel, HttpBase, LoginParams } from '@/config/model/userModel';
import router, { dynamicMenu, routesMenu } from '@/router';
import { getMenusList } from '@/router/menus';
import { authLogin, authLogout } from '@/config/api/common/api';
import actions from '@/micro/shared/actions';
import { setDictionaryList } from '@/utils/dictionary';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
interface UserState {
  userInfo: any;
  token?: string;
  tenantid: string;
  loginInfo: any;
  menuPermission: boolean;
  labelDataList: any
}

const filterRouter = (menuList: any[]) => {//过滤路由的方法

  let arrMenus:any = [];

  routesMenu.forEach((item:any)=>{
    if( item.children && item.children.length ){
      arrMenus.push( ...item.children )
    }else{
      arrMenus.push(item)
    }
  });

  menuList.forEach((item:any)=>{
    if(item.childMenu){
      item.children = item.childMenu
      delete item.childMenu;
    } 
    if(  item.sys.value !== '1'){
      if(item.devRouteRes){
        initMenu(item)
      }
    }else{
      let parantObj:any;
      if( item.type && item.type.value === '0' ){
        item.name = item.name;
        item.path = '/';
        item.meta = Object.assign({},
          {
            icon: item.icon,
            title: item.name,
            hidden: item.isDisplay === 1 ? false: true
          }
        ) ;
      }else{
        parantObj = arrMenus.find((menu:any)=>menu.name === item.devRouteRes.route) || {};
        item.name = item.devRouteRes.route;
        item.path = '/';
        item.meta = Object.assign({},
          parantObj ? parantObj.meta : {},
          {
            icon: item.icon,
            title: item.devRouteRes.name,
            hidden: item.isDisplay === 1 ? false: true
          }
        ) ;
      }
      if( item.children && item.children.length ){
        item.children.forEach((child:any)=>{
          let obj:any = arrMenus.find((menu:any)=>menu.name === child.devRouteRes.route) || null;
          child.name = child.devRouteRes.route;
          child.path = child.devRouteRes.path;
          child.meta = Object.assign({},
            obj ? obj.meta : {},
            {
              icon: child.icon,
              title: child.devRouteRes.name,
              hidden: child.isDisplay === 1 ? false: true
            }
          ) ;
          child.component = obj?.component;
        })
      }else{
        item.component = parantObj?.component;
      }
    }
  })

  return menuList

  function initMenu(obj){
    obj = Object.assign( obj, {
      name: obj.devRouteRes.route,
      path: autoPath(obj),
      hidden: obj.isDisplay === 0 ? true: false ,
      meta: {
        icon: obj.icon,
        title: obj.devRouteRes.name
      },
    }) ;
    if( obj.children && obj.children.length ){
      let arr =  obj.children.map((item)=>({
        name: item.devRouteRes?.route,
        path: autoPath(item),
        hidden: item.isDisplay === 0 ? true: false ,
        meta: {
          icon: item.icon,
          title: item.devRouteRes?.name
        },
        component: () => import('@/views/layout/qiankun-view.vue')
      }))
      obj.children = arr;
    }else{
      obj.component = () => import('@/views/layout/qiankun-view.vue');
    }
  }

  function autoPath(obj){
    if( !obj.devRouteRes ){
      console.log('路由数据报错',obj);
      return '/error'
    }
    let path = obj.devRouteRes.path;
    if( obj.sys && obj.sys.text ){
      path = '/' + obj.sys.text.toLowerCase() + '-web' + path;
    }
    return path
  }
  
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    userInfo: null, //用户信息
    token: getToken(), //token
    tenantid: '', //租户id
    loginInfo: null,  //登录返回信息
    menuPermission: false,  //代表着菜单权限
    labelDataList: [],  //历史标签
  }),
  getters: {
    getUserInfo():any {
      return this.userInfo || getAuthCache(USER_INFO_KEY) || {};
    },
    getLoginInfo(): any {
      return this.loginInfo || getAuthCache(LOGIN_INFO_KEY) || {};
    },
    getToken(): string {
      return this.token || getAuthCache<string>(TOKEN_KEY);
    },
    getTenant(): string | number {
      return this.tenantid || getAuthCache<string | number>(TENANT_ID);
    },
    getLabelDataList(): any {
      return this.labelDataList ;
    },
  },
  actions: {
    //接收子应用事件
    setReceive(item:any){
      console.log('子应用事件数据',item);
      switch (item.key) {
        case 'logout':
          this.logout()
        break;
      }
    },
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      setAuthCache(TOKEN_KEY, info);
    },
    setLabelDataList(data:any) {
      
      let boo = this.labelDataList.find((item) => {
        return item.name == data.name;
      });
      if (!boo) {
        if( this.labelDataList.length >=10 ){
          this.setDeleteLabelDataList(0);
        }
        this.labelDataList.push({
          name: data.name,
          path: data.path,
          title: data.meta.title,
        });
      }
    },
    //当标签关闭的时候删除labelDataList 对应的数据
    setDeleteLabelDataList(index) {
      this.labelDataList.splice(index, 1);
    },
    setMenuPermission(has:boolean) {
      this.menuPermission = has; // for null or undefined value
    },
    setUserInfo(info: any | null) {
      this.userInfo = info;
      
      setAuthCache(USER_INFO_KEY, info);
    },
    setLoginInfo(info: any | null) {
      this.loginInfo = info.data;
      setAuthCache(LOGIN_INFO_KEY, info.data);
    },
    setTenant(id: any) {
      this.tenantid = id;
      setAuthCache(TENANT_ID, id);
    },
    /**
     * 登录事件
     */
     async login(
      params: LoginParams & {
        account: string;
        captcha: string;
        language?: string;
        password: string;
      }
    ): Promise<HttpBase<GetUserInfoModel> | null> {
      try {
        const data = await authLogin(params);
        this.setToken(data.data.token);  //存token
        this.setLoginInfo(data);  //存登录返回信息
        actions.setGlobalState({ token: data.data.token });  //微前端框架传参
        return this.afterLoginAction()
      } catch (error) {
        return Promise.reject(error);
      }
    },
    /**
     * 登录完成处理
     */
     async afterLoginAction( data?: any): Promise<any | null> {
      if (!this.getToken) return null;
      setDictionaryList();
      let listPermissions:any = await getMenusList();
      if(listPermissions){
        this.setUserInfo(listPermissions);
        // await this.addRouter(listPermissions);
        console.log('动态菜单列表', router.options.routes);
        //跳转首页
        await router.push({name : 'BaseDataWatermark'})
      }
      
    },

    /**
     * 退出登录
     */
     async logout() {
      if( qiankunWindow.__POWERED_BY_QIANKUN__  ){
        actions.updateState({ key: 'logout' });
      }else if (this.getToken) {
        try {
          const res = await authLogout();
          this.clearUserData();
        } catch {
          this.clearUserData();
        }
      }else{
        this.clearUserData();
      }
    },

    /**
     * 清除用户数据
     */
    clearUserData() {
      this.setToken('');
      setAuthCache(TOKEN_KEY, '');
      this.setUserInfo('');
      this.setLoginInfo('');
      this.setMenuPermission(false);
      router.push({name : 'Login'})
     },

    async addRouter(listPermissions:any = this.getUserInfo){
      if( listPermissions.length ){
        const routes:any = filterRouter(listPermissions);
        // const allroute:any = [...routesMenu,...routes];
        router.options.routes = [];
        routes.forEach(item => {
          router.addRoute(item)
          router.options.routes.push(item)
        });
        console.log('整理好的路由',router.options.routes);
      }
      this.setMenuPermission(true);
    },
  }
});

//需要在设置之外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}